﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;

public class ProfileScene : Scene
{   
    enum SCENEMODE
    {
        profile,
        character,
    }

    public MemberModel m_SelectMember = null;

    SCENEMODE m_SceneMode = SCENEMODE.profile;
 
    #region Left List 관련 변수
    int m_MembersMax = 0;
    List<int> m_MembersNo = new List<int>();

    public Animation m_LeftListAni;
    public GameObject m_LeftListOrizin;
    const float ListMemberStartY = 135.0f;
    const float ListMemberGap = 195.0f;
    [HideInInspector]
    public List<Oc_MemberListItem> m_LeftListItems = new List<Oc_MemberListItem>();
    #endregion

    #region 애니메이션 변수
    public GameObject m_InfoUIRoot;           //인포 패널 등장 퇴장 애니   
    public Animation m_SortAni;
    #endregion    

    #region 길드원 정렬 관련 변수

    public UILabel[] m_SortKindsLabel;

    bool m_IsSortMenuOn = false;
    SortKind m_SortKind = SortKind.Level;

    bool m_IsDescending = true;

    string tempString0 = null;
    string tempString1 = null;
    string tempString2 = null;
    #endregion  


    #region leftlist 무빙 관련
    public UIScrollView m_LeftScrollView;
    const float LeftListScrollViewStartPositonY = -128.0f;
    const float LeftListScrollViewStartOffSetY = -300.0f;
    public bool m_IsLeftListMoving = false;
   
    void UpdateLeftScrollView()
    {
        if (m_IsLeftListMoving)
        {
            SpringPanel sp = m_LeftScrollView.GetComponent("SpringPanel") as SpringPanel;
            if (sp != null)
                sp.enabled = false;

            UIPanel up = m_LeftScrollView.panel;
            Vector2 offSet = up.clipOffset;
            offSet.y = LeftListScrollViewStartOffSetY - m_LeftScrollView.transform.localPosition.y + LeftListScrollViewStartPositonY;
            up.clipOffset = offSet;
        }
    }
    #endregion


    public GameObject m_TraitIncEffect;

    public Transform m_LightProbeAnchorRoot;


    #region 메뉴 컨트롤 부분
    void SetSortMenuUI(int num)        // 소트 메뉴 라벨 설정
    {
        m_SortKind = (SortKind)(((int)m_SortKind + num) % 3);   // 각 상황마다 대응

        switch (m_SortKind)
        {
            case SortKind.Level:
                m_SortKindsLabel[0].text = tempString0;
                m_SortKindsLabel[1].text = tempString1;
                m_SortKindsLabel[2].text = tempString2;
                break;
            case SortKind.Rare:
                m_SortKindsLabel[0].text = tempString1;
                m_SortKindsLabel[1].text = tempString2;
                m_SortKindsLabel[2].text = tempString0;
                break;
            case SortKind.Inhance:
                m_SortKindsLabel[0].text = tempString2;
                m_SortKindsLabel[1].text = tempString0;
                m_SortKindsLabel[2].text = tempString1;
                break;
        }

        SortMember();
        SetLeftListUI();

        if (m_SelectMember == null)
        {
            m_SelectMember = m_LeftListItems[0].m_MemberModel;
        }

        for (int i = 0; i < m_LeftListItems.Count; i++)
        {
            if (m_SelectMember.no == m_LeftListItems[i].m_MemberModel.no)
                m_LeftListItems[i].SetOn(false);
            else
                m_LeftListItems[i].SetOff();
        }
    }

    public void RefreshLeftListAndInfo()
    {
        SetSortMenuUI(m_SortKind);
    }

    void SetSortMenuUI(SortKind kind)        // 소트 메뉴 라벨 설정
    {
        m_SortKind = kind;   // 각 상황마다 대응

        switch (m_SortKind)
        {
            case SortKind.Level:
                m_SortKindsLabel[0].text = tempString0;
                m_SortKindsLabel[1].text = tempString1;
                m_SortKindsLabel[2].text = tempString2;
                break;
            case SortKind.Rare:
                m_SortKindsLabel[0].text = tempString1;
                m_SortKindsLabel[1].text = tempString2;
                m_SortKindsLabel[2].text = tempString0;
                break;
            case SortKind.Inhance:
                m_SortKindsLabel[0].text = tempString2;
                m_SortKindsLabel[1].text = tempString0;
                m_SortKindsLabel[2].text = tempString1;
                break;
        }

        SortMember();
        SetLeftListUI();

        for (int i = 0; i < m_LeftListItems.Count; i++)
        {
            m_LeftListItems[i].SetOff();
        }

        if (m_SceneMode == SCENEMODE.character)
        {
            if (m_SelectMember == null)
                m_SelectMember = m_LeftListItems[0].m_MemberModel;

            UpdateInfoUI(m_SelectMember);

            for (int i = 0; i < m_LeftListItems.Count; i++)
            {
                if (m_LeftListItems[i].m_MemberModel.no == m_SelectMember.no)
                    m_LeftListItems[i].SetOn(false);
            }
        }        
    }

    void SortMember()
    {
        m_MembersNo.Clear();

        List<MemberModel> tList = new List<MemberModel>();

        if (m_SceneMode == SCENEMODE.character)
        {
            foreach (KeyValuePair<string, MemberModel> t in UserData.Instance.userModel.members_dic)
            {
                tList.Add(t.Value);
            }
        }        

        int max = tList.Count;
        for (int i = 0; i < max - 1; i++)
        {
            for (int j = 0; j < max - 1; j++)
            {
                switch (m_SortKind)
                {
                    case SortKind.Level:
                        {
                            if (tList[j].level < tList[j + 1].level)
                            {
                                MemberModel t = tList[j];
                                tList[j] = tList[j + 1];
                                tList[j + 1] = t;
                            }
                        }
                        break;
                    case SortKind.Rare:
                        {
                            if (tList[j].rarity < tList[j + 1].rarity)
                            {
                                MemberModel t = tList[j];
                                tList[j] = tList[j + 1];
                                tList[j + 1] = t;
                            }
                        }
                        break;
                    case SortKind.Inhance:
                        {
                            if (tList[j].strengthening < tList[j + 1].strengthening)
                            {
                                MemberModel t = tList[j];
                                tList[j] = tList[j + 1];
                                tList[j + 1] = t;
                            }
                        }
                        break;
                }
            }
        }

        for (int i = 0; i < max; i++)
        {
            if (m_IsDescending)
                m_MembersNo.Add(tList[i].no);
            else
                m_MembersNo.Add(tList[max - i - 1].no);
        }
    }

    void OnLoginErrCallback(ResponseModel<UserModel> recvData)
    {
        Debug.LogError("OnLoginErrCallback");
    }

    void OnLoginCallback(ResponseModel<UserModel> userData)
    {
        UserData.Instance.userModel = userData.data;
        StartCoroutine("StartSceneWithDelay");
    }

    public override void AwakeScene()
    {
        Instance = this;

        //left리스트 드래그 스크롤뷰 설정
        UIDragScrollView tDs = m_LeftListOrizin.GetComponent("UIDragScrollView") as UIDragScrollView;
        tDs.scrollView = m_LeftScrollView;

        Popup_Blur.ClearAll();


        // test version code  /////////////////////////////////////////////
        /**/
        if (UserData.Instance.userModel == null)
        {
            LoadingScene.TestInit();
            /**/
            NetworkManager.Instance.C2S_LOGIN(AuthPlatformID.None, "hshshs", string.Empty, OnLoginCallback, OnLoginErrCallback);
        }
        /////////////////////////////////////////////////////////////////
        else
        {
            StartCoroutine("StartSceneWithDelay");
        }
    }

    IEnumerator StartSceneWithDelay()
    {
        yield return new WaitForSeconds(0.0f);

        tempString0 = TextController.GetStringWithId("uiCommonTextLevel");
        tempString1 = TextController.GetStringWithId("uiCommonTextRarityDo");
        tempString2 = TextController.GetStringWithId("uiCommonTextEnhance");

        //일단 레벨순으로 설정
        m_SortKindsLabel[0].text = tempString0;
        m_SortKindsLabel[1].text = tempString1;
        m_SortKindsLabel[2].text = tempString2;

        m_MembersMax = UserData.Instance.userModel.members_dic.Count;

        SortMember();

        CreateList();

        StartSceneAni();
    }

    void CreateList()
    {
        // 정렬메뉴 x -700 에서 씬 시작
        Vector3 pos = m_SortAni.transform.localPosition;
        pos.x = -700.0f;
        m_SortAni.transform.localPosition = pos;

        SortMember();

        // 레프트 메뉴 x -700 에서 씬 시작
        GameObject temp = null;
        Oc_MemberListItem tempML = null;
        for (int i = 0; i < m_MembersMax; i++)
        {
            if (i > 0)
                temp = Instantiate(m_LeftListOrizin) as GameObject;
            else
                temp = m_LeftListOrizin;

            temp.transform.parent = m_LeftListOrizin.transform.parent;
            temp.transform.localScale = m_LeftListOrizin.transform.localScale;
            temp.name = string.Format("memberList_A{0}", i + 1);
            tempML = temp.GetComponent("Oc_MemberListItem") as Oc_MemberListItem;
            tempML.SetList(UserData.Instance.userModel.members_dic[m_MembersNo[i].ToString()]);
            m_LeftListItems.Add(tempML);
        }


        if (m_SelectMember == null)
            m_SelectMember = m_LeftListItems[0].m_MemberModel;
        UpdateInfoUI(m_SelectMember);

        for (int i = 0; i < m_LeftListItems.Count; i++)
        {
            if (m_LeftListItems[i].m_MemberModel.no == m_SelectMember.no)
                m_LeftListItems[i].SetOn(false);
        }
    }

    void SetLeftListPos()
    {
        Vector3 pos = Vector3.zero;
        float OnListGap = 0.0f;
        for (int i = 0; i < m_MembersMax; i++)
        {
            pos = m_LeftListItems[i].transform.localPosition;
            pos.y = ListMemberStartY - (ListMemberGap * i) - OnListGap;
            m_LeftListItems[i].transform.localPosition = pos;

            if (m_SelectMember != null)
            {
                if (m_LeftListItems[i].m_MemberModel.no == m_SelectMember.no)
                    OnListGap = 20.0f;
            }
        }
    }

    void SetLeftListUI()
    {
        for (int i = 0; i < m_MembersMax; i++)
        {
            if (i < m_MembersNo.Count)
            {
                m_LeftListItems[i].gameObject.SetActive(true);
                m_LeftListItems[i].SetList(UserData.Instance.userModel.members_dic[m_MembersNo[i].ToString()]);
            }
            else
                m_LeftListItems[i].gameObject.SetActive(false);
        }
    }

    public override void StartScene()
    {
        //StartSceneAni();

        //Localization.language = "text_ko";
    }


    void InfoUIAni(bool isUp, float delay)
    {
        float time = 1.0f;
        if (isUp)
        {
            iTween.MoveTo(m_InfoUIRoot, iTween.Hash("islocal", true, "delay", delay, "time", time, "y", -123.0f, "oncompletetarget", gameObject, "oncomplete", "OnFInishedInfoUIAnimation"));
        }
        else
        {
            iTween.MoveTo(m_InfoUIRoot, iTween.Hash("islocal", true, "delay", delay, "time", time, "y", -1500.0f));
        }
    }

    public void OnFInishedInfoUIAnimation()
    {
        Debug.LogError("111");
        if (UserData.Instance.userModel.questInfo.questId == 1 && UserData.Instance.userModel.questInfo.state == 3)
        {
            Debug.LogError("111");
            GameObject obj = Resources.Load("Prefab/UI/touch") as GameObject;
            GameObject questMarker = Instantiate(obj) as GameObject;
            questMarker.transform.parent = m_InfoUIRoot.transform;
            questMarker.transform.localPosition = new Vector3(442f, 445f, 0f);
            questMarker.transform.localScale = Vector3.one;
        }
    }

    public void StartSceneAni()
    {
        {
            SetActiveHelpButton(false);

            //infoList 패널 올라오는 애니
            Vector3 pos = m_InfoUIRoot.transform.localPosition;   //인포 패널 시작 y -1500으로 시작
            pos.y = -1500.0f;
            m_InfoUIRoot.transform.localPosition = pos;
            InfoUIAni(true, 0.5f);

            MemberListAni(true);
        }
    }


    public void EndSceneAni()
    {
        m_LeftListAni.Play("info_detail_list OUT");
        InfoUIAni(false, 0);
    }


    void UpdateInfoUI(MemberModel tempModel)
    {
        //membermodel
        SetCharacterModel(tempModel);

        OC_InfoUIWithScroll.instance.UpdateInfoUI(tempModel);

        //// 아이템 있는지 없는지 판단해서 웨폰 아이콘 유무 판별
        //Transform leftRight = m_WeaponRoot.Find("LeftItem");
        //Oc_ItemShowBox sb = leftRight.GetComponent("Oc_ItemShowBox") as Oc_ItemShowBox;
        //sb.SetItem(tempModel.leftItem, true);
        //leftRight = m_WeaponRoot.Find("RightItem");
        //sb = leftRight.GetComponent("Oc_ItemShowBox") as Oc_ItemShowBox;
        //sb.SetItem(tempModel.rightItem, false);

        //리스트 포지션 이동
        SetLeftListPos();
    }


    public override void ButtonTouch(Collider collider)  // 버튼 터치 (터치 시작 끝 같은 오브젝트일때 터치 끝 시점에 호출)
    {
        Debug.Log(collider.name);

        if (collider.name.Contains("memberList_A"))
        {
            Oc_MemberListItem Choise_ML = collider.GetComponent("Oc_MemberListItem") as Oc_MemberListItem;

            if (m_SceneMode == SCENEMODE.character)
            {
                if (m_SelectMember.no != Choise_ML.m_MemberModel.no)      // 이전 선택 길드원과 다를때
                {
                    m_SelectMember = Choise_ML.m_MemberModel;
                    UpdateInfoUI(m_SelectMember);
                    // 다른 인원 선택시 인포 리스트 초기화 
                    OC_InfoUIWithScroll.instance.m_SelectListNum = -1;
                    OC_InfoUIWithScroll.instance.MoveList();
                }
            }           

            foreach (Oc_MemberListItem t_ML in m_LeftListItems)
            {
                if (t_ML.Equals(Choise_ML))
                    t_ML.SetOn(true);
                else
                    t_ML.SetOff();
            }
        }
        else if (collider.name.Contains("Button_Sort_"))
        {
            if (m_IsSortMenuOn)
            {
                string buttonName = collider.gameObject.name.Replace("Button_Sort_", "");
                int num = System.Convert.ToInt32(buttonName);
                SetSortMenuUI(num);
                m_SortAni.Play("sort_close");
            }
            else
            {
                m_SortAni.Play("sort_open");
            }
            m_IsSortMenuOn = !m_IsSortMenuOn;
        }
        else
        {
            switch (collider.gameObject.name)
            {
                case "Button_Init":
                    {
                    
                    }
                    break;

                case "Button_Equip":
                    {
                        GoProfileMenu();
                    }
                    break;

                case "Button_GoPowerUp":           // 강화 버튼
                    {
                       
                    }
                    break;
                case "Button_Detail":
                    {
                        Popup_Info_detail popupSc = PopupManager.PushPopup(PopupKind.Info_detail) as Popup_Info_detail;
                        popupSc.SetPopupWithMember(m_SelectMember);
                    }
                    break;
                case "Button_Dismiss":
                    {
                        if (UserData.Instance.userModel.regions.isDispatchingMember(m_SelectMember.no))
                        {
                            Popup_OneButton popupSc = PopupManager.PushPopup(PopupKind.OneButton) as Popup_OneButton;
                            popupSc.SetPopupWithTitleAndBody(TextController.GetStringWithId("uiCommonTextwarning"), TextController.GetStringWithId("uiCommonTextDispatchCaution1"));
                        }
                        else
                        {
                            Popup_TwoButton popupSc = PopupManager.PushPopup(PopupKind.TwoButton) as Popup_TwoButton;
                            popupSc.SetPopupWithTitleAndBody(TextController.GetStringWithId("uiCharInfoDismiss"), string.Format(TextController.GetStringWithId("uiPopupCharInfoDismiss"),
                                TextController.GetStringWithId(string.Format("charName{0}", m_SelectMember.name))));
                            popupSc.SetPopupWithYesNoString(TextController.GetStringWithId("uiCharInfoDismiss"), TextController.GetStringWithId("uiCommonTextNo"));
                            popupSc.SetEventOK(gameObject, "OnDismissPopup");
                        }
                    }
                    break;
                case "Button_Visual":
                    {
                        
                    }
                    break;
                case "Button_GoItem":
                    {
                        GoProfileMenu();
                    }
                    break;
                case "Button_updown":
                    m_IsDescending = !m_IsDescending;

                    collider.transform.Find("Up").gameObject.SetActive(!m_IsDescending);
                    collider.transform.Find("Down").gameObject.SetActive(m_IsDescending);

                    SetSortMenuUI(m_SortKind);
                    break;

                case "Button_Sort":
                    {
                        if (m_IsSortMenuOn)
                            m_SortAni.Play("sort_close");
                        else
                        {
                            //for (int i = 0; i < SortingNum; i++)
                            //{
                            //    m_SortKindsLabel[i].text = m_SortKindsLabel[i];
                            //}

                            m_SortAni.Play("sort_open");
                        }

                        m_IsSortMenuOn = !m_IsSortMenuOn;
                    }
                    break; 
                case "Button_Infopopup":
                    PopupManager.PushPopup(PopupKind.Character_Info);
                    Debug.Log("Button_Infopopup");
                    break;

                case "Button_Back":
                    BackButton();
                    break;
            }
        }
    }       

    void IgnoreTouch()
    {
        IsAbleControl = false;
        StartCoroutine("UnignoreTouch");
    }

    IEnumerator UnignoreTouch()
    {
        yield return new WaitForSeconds(0.5f);
        IsAbleControl = true;
    }

    void GocharacterMenu()
    {
        IgnoreTouch();

        SetModelRotateButton(true);

        SoundController.PlaySound("UI_screen_slide");

        SetActiveHelpButton(false);

        SCENEMODE PreSceneMode = m_SceneMode;
        m_SceneMode = SCENEMODE.character;

        // 멤버리스트 인포로 이동
        //m_MemberListRoot.transform.parent = GameObject.Find("infoPanel").transform.Find("Root");
        // 드래그 이벤트 취소
        foreach (Oc_MemberListItem t in m_LeftListItems)
        {
            t.m_EventRecieaver = null;
        }


        MemberListAni(true);
        
        SetSortMenuUI(m_SortKind);
    }

    void EndLeftListMove()
    {
        m_IsLeftListMoving = false;
    }

    void LeftListCollidersOn()
    {
        for (int i = 0; i < m_LeftListItems.Count; i++)
        {
            m_LeftListItems[i].collider.enabled = true;
        }
    }

    public void MemberListAni(bool isIn)
    {
        if (isIn)
        {
            //들어오는 애니는 무조건 스크롤 부분 초기화 해서 들어옴
            Vector3 pos = m_LeftScrollView.transform.localPosition;
            pos.y = LeftListScrollViewStartPositonY;
            m_LeftScrollView.transform.localPosition = pos;

            UIPanel up = m_LeftScrollView.panel;
            Vector2 offSet = up.clipOffset;
            offSet.y = LeftListScrollViewStartOffSetY - m_LeftScrollView.transform.localPosition.y + LeftListScrollViewStartPositonY;
            up.clipOffset = offSet;


            LeftListCollidersOn();

            // Vector3 pos = m_SortAni.transform.localPosition;
            pos = m_SortAni.transform.localPosition;
            pos.x = -700.0f;
            m_SortAni.transform.localPosition = pos;

            iTween.MoveTo(m_SortAni.gameObject, iTween.Hash("islocal", true, "x", -3.0f, "time", 0.5f, "easetype", "spring"));

            int maxAni = System.Math.Min(m_LeftListItems.Count, 6);     // 한번에 보여줄수있는 최대 리스트 갯수 6개 이하 예외 처리
            for (int i = 0; i < maxAni; i++)
            {
                pos = m_LeftListItems[i].transform.localPosition;
                pos.x = -700.0f;
                m_LeftListItems[i].transform.localPosition = pos;

                iTween.MoveTo(m_LeftListItems[i].gameObject, iTween.Hash("islocal", true, "x", 1.0f, "time", 0.5f, "easetype", "spring", "delay", (i * 0.1f)));
            }

            for (int i = maxAni; i < m_LeftListItems.Count; i++)
            {
                pos = m_LeftListItems[i].transform.localPosition;
                pos.x = 1.0f;
                m_LeftListItems[i].transform.localPosition = pos;
            }
        }
        else
        {
            m_IsLeftListMoving = true;      // 나가는 에니만 리스트 올림

            iTween.MoveTo(m_LeftScrollView.gameObject, iTween.Hash("islocal", true, "y", LeftListScrollViewStartPositonY, "time", 0.2f, "easetype", "spring",
                "oncompletetarget", gameObject, "oncomplete", "EndLeftListMove"));

            for (int i = 0; i < m_LeftListItems.Count; i++)  // 아웃 무빙시 콜라이더 디스에이블
            {
                m_LeftListItems[i].collider.enabled = false;
            }

            Vector3 pos = m_SortAni.transform.localPosition;
            pos.x = -3.0f;
            m_SortAni.transform.localPosition = pos;

            iTween.MoveTo(m_SortAni.gameObject, iTween.Hash("islocal", true, "x", -700.0f, "time", 0.5f, "easetype", "spring"));      // 나가는 애니

            int maxAni = System.Math.Min(m_LeftListItems.Count, 6);     // 한번에 보여줄수있는 최대 리스트 갯수 6개 이하 예외 처리
            for (int i = 0; i < maxAni; i++)
            {
                pos = m_LeftListItems[i].transform.localPosition;
                pos.x = 1.0f;
                m_LeftListItems[i].transform.localPosition = pos;

                if (i == maxAni - 1)  // 마지막 놈에 엔드 함수 호출
                    iTween.MoveTo(m_LeftListItems[i].gameObject, iTween.Hash("islocal", true, "x", -700.0f, "time", 0.5f, "easetype", "spring", "delay", (i * 0.1f))); // 나가는 애니                
                else
                    iTween.MoveTo(m_LeftListItems[i].gameObject, iTween.Hash("islocal", true, "x", -700.0f, "time", 0.5f, "easetype", "spring", "delay", (i * 0.1f))); // 나가는 애니
            }

            for (int i = maxAni; i < m_LeftListItems.Count; i++)
            {
                pos = m_LeftListItems[i].transform.localPosition;
                pos.x = -700.0f;
                m_LeftListItems[i].transform.localPosition = pos;
            }
        }
    }


    void GoProfileMenu()
    {
        IgnoreTouch();

        SetModelRotateButton(false);

        SoundController.PlaySound("UI_screen_slide");

        SetActiveHelpButton(false);

        SCENEMODE PreSceneMode = m_SceneMode;
        m_SceneMode = SCENEMODE.profile;        
    }


    public override void BackButton()
    {
        if (m_SceneMode == SCENEMODE.character)
        {
        }
        else if (m_SceneMode == SCENEMODE.profile)
        {          
        }
    }
    #endregion

    void GetQuestInfo()
    {
        NetworkManager.Instance.C2S_GET_QUESTINFO(QuestManager.instance.ResponseGetQuestInfo);
    }
       

    // 동적 케릭터 모델 관리
    GameObject m_3DPosition = null;
    [HideInInspector]
    public GameObject m_3DModel = null; // 케릭터 루트
    public GameObject m_3DModelRotateButton;

    Vector3 m_OrizinAngle;

    void SetModelRotateButton(bool isOn)
    {
        m_3DModelRotateButton.SetActive(isOn);

        if (isOn)
            iTween.RotateTo(m_3DModel, iTween.Hash("islocal", true, "y", m_OrizinAngle.y, "time", 1.0f));
        else
            m_3DModel.transform.localRotation = Quaternion.Euler(m_OrizinAngle);
    }

    void SetCharacterModel(MemberModel selectModel)
    {
        if (m_3DPosition == null)
            m_3DPosition = GameObject.Find("LobbyVersion/Position");

        string modelName = GameData.Inst.ModelDefineDic[selectModel.model];

        if (m_3DModel != null && m_3DModel.name.Equals(modelName))  // 같은 위치 케릭터면 이전 케릭터 재사용
            return;
        if (m_3DModel != null)
            Destroy(m_3DModel);

       // m_3DModel = BattleResManager.CreatePawn((int)selectModel.model, false);

        RuntimeMeshChanger rtmc = m_3DModel.GetComponent("RuntimeMeshChanger") as RuntimeMeshChanger;
        if (rtmc != null)
        {
            // Debug.Log("adfadfadsf");
            rtmc.ChangeToLow();
        }

        //m_3DModel.name = modelName;

        //Transform root = m_3DPosition.transform;
        //int nRemoveIndex = modelName.IndexOf("_", StringComparison.Ordinal);
        //string model_no = modelName;
        //if (nRemoveIndex != -1)
        //    model_no = modelName.Remove(nRemoveIndex);

        //m_OrizinAngle = m_3DModel.transform.localRotation.eulerAngles;

        //for (int j = 0; j < root.childCount; j++)
        //{
        //    int nIndex = root.GetChild(j).name.IndexOf("_", StringComparison.Ordinal);
        //    string rootName = root.GetChild(j).name;
        //    if (nIndex != -1)
        //        rootName = rootName.Remove(nIndex);

        //    if (rootName.Equals(model_no))
        //    {
        //        m_3DModel.transform.parent = root.GetChild(j);
        //        m_3DModel.transform.localScale = Vector3.one;
        //        m_3DModel.transform.localPosition = Vector3.zero;
        //        m_3DModel.transform.localRotation = Quaternion.Euler(Vector3.zero);

        //        m_3DModel.transform.parent.Find("floor").gameObject.SetActive(true);
        //    }
        //    else
        //        root.GetChild(j).Find("floor").gameObject.SetActive(false);
        //}

        m_3DModel.name = modelName;

        Transform root = m_3DPosition.transform;
        int nRemoveIndex = modelName.IndexOf("_", StringComparison.Ordinal);
        string model_no = modelName;
        bool isHaveUnderBar = (nRemoveIndex != -1);

        m_OrizinAngle = m_3DModel.transform.localRotation.eulerAngles;

        for (int j = 0; j < root.childCount; j++)
        {
            bool isCorrectRoot = false;
            if (isHaveUnderBar)
            {
                string rootName = root.GetChild(j).name.Remove(4);
                string childName = model_no.Remove(4);
                isCorrectRoot = rootName.Equals(childName);
            }
            else    // 언더바 안들은 애들은 이전 방식으로 찾는다
            {
                string rootName = root.GetChild(j).name;
                string childName = model_no;
                isCorrectRoot = rootName.Contains(childName);
            }

            if (isCorrectRoot)
            {
                m_3DModel.transform.parent = root.GetChild(j);
                m_3DModel.transform.localScale = Vector3.one;
                m_3DModel.transform.localPosition = Vector3.zero;
                m_3DModel.transform.localRotation = Quaternion.Euler(Vector3.zero);

                m_3DModel.transform.parent.Find("floor").gameObject.SetActive(true);
            }
            else
                root.GetChild(j).Find("floor").gameObject.SetActive(false);
        }

        var ani = m_3DModel.MakeComponent<Animation>();
        ani["lobby01"].clip.wrapMode = WrapMode.Loop;
        ani.Play("lobby01");

        AttachWeapon(selectModel, m_3DModel);

        AttachAnchor();
    }

    void AttachAnchor()
    {
        SkinnedMeshRenderer[] tList = m_3DModel.GetComponentsInChildren<SkinnedMeshRenderer>();

        if (tList != null)
        {
            Transform tempAnchor = m_LightProbeAnchorRoot.Find(m_3DModel.name);

            for (int i = 0; i < tList.Length; i++)
            {
                tList[i].lightProbeAnchor = tempAnchor;
            }
        }
    }

    public override void HelpButton()
    {
        switch (m_SceneMode)
        {
            case SCENEMODE.character:
                {
                    Popup_Tutorial pt = PopupManager.PushPopup(PopupKind.Tutorial) as Popup_Tutorial;
                    pt.SetPopupWithTutorialKind(TutorialKind.helpCharInfoInfoA);
                    pt.SetEventOK(gameObject, "OnTutorialNext");
                }
                break;
        }
    }

    void OnTutorialNext()
    {
        Popup_Tutorial pt = PopupManager.PushPopup(PopupKind.Tutorial) as Popup_Tutorial;
        pt.SetPopupWithTutorialKind(TutorialKind.helpCharInfoInfoB);
    }


    GameObject[] m_WeaponModels = new GameObject[2];
    BattleCharInfo AttachWeapon(GameObject _parent, Item L_item, Item R_item)
    {
        for (int i = 0; i < 2; i++)
        {
            if (m_WeaponModels[i] != null)
                DestroyImmediate(m_WeaponModels[i]);
        }

        int[] itemModelId = new int[2];

        if (R_item != null)
        {
            //Debug.Log(R_item.itemInfo);
            itemModelId[0] = R_item.itemInfo.modelID;
        }


        if (L_item != null)
            itemModelId[1] = L_item.itemInfo.modelID;

        BattleCharInfo charInfo = _parent.GetComponent("BattleCharInfo") as BattleCharInfo;

        m_WeaponModels = BattleResManager.AttachWeapon(_parent, charInfo, itemModelId, true);

        return charInfo;
    }

    public BattleCharInfo AttachWeapon(MemberModel member, GameObject _parent)
    {
        return AttachWeapon(_parent, member.leftItem, member.rightItem);
    }

    public void ChangeWepon(Item item)
    {
        if (item == null)    // 장착 중 무기로 변경  
        {
            AttachWeapon(m_SelectMember, m_3DModel);
        }
        else
        {
            if (item.itemInfo.part == 1)
                AttachWeapon(m_3DModel, null, item);
            else if (item.itemInfo.part == 2)
                AttachWeapon(m_3DModel, item, null);
            else
                AttachWeapon(m_3DModel, item, item);
        }
    }
}